package com.hyts.serialize.binary.jdk;

import com.hyts.serialize.bean.JdkBean;
import com.hyts.serialize.factory.JdkBeanFactory;
import com.hyts.serialize.binary.BinarySerializeHandler;
import lombok.NoArgsConstructor;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;

/**
 * project-name:coffice-toolbox
 * package-name:com.hyts.serialize.handler.jdk
 * author:Libo/Alex
 * create-date:2019-06-21 22:07
 * copyright:libo-hyts-github
 * email:libo2dev@aliyun.com
 * description:此类主要用于: jdk原生的序列化方式
 */
@NoArgsConstructor
public class JdkSerializeHandler extends BinarySerializeHandler<JdkBean,JdkBean> {


    @Override
    public BinarySerializeHandler<JdkBean,JdkBean> build() {
        setResult(JdkBeanFactory.builder().build().create());
        return this;
    }

    @Override
    public BinarySerializeHandler<JdkBean, JdkBean> build(JdkBean param) {
        setResult(JdkBeanFactory.builder().build().create(param));
        return this;
    }

    @Override
    public byte[] serialize(Object value) {
        try {
            getResult().getObjectOutputStream().writeObject(value);
            return getResult().getByteArrayOutputStream().toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                getResult().getObjectOutputStream().close();
                getResult().getByteArrayOutputStream().close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return new byte[0];
    }

    @Override
    public Object deserialize(byte[] param) {
        try {
            getResult().setByteArrayInputStream(new ByteArrayInputStream(param));
            getResult().setObjectInputStream(new ObjectInputStream(getResult().getByteArrayInputStream()));
            return getResult().getObjectInputStream().readObject();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }finally {
            try {
                getResult().getByteArrayInputStream().close();
                getResult().getObjectInputStream().close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return new byte[0];
    }

    @Override
    public <T> T deserialize(byte[] byteData, Class<T> clazzType) {
        return (T) deserialize(byteData);
    }

    @Override
    public <T> T serialize(T byteData, Class<T> clazzType) {
        throw new UnsupportedOperationException("不支持此方法-protostuff专属使用");
    }
}
